package {
	
	import alternativa.engine3d.core.Mesh;
	import alternativa.types.Texture;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;

	public class ObjetLoader extends Mesh {
		// Eléments à charger
		protected var bindings:Array;
		// Message de status
		protected var loadingMessage:String;
		// Fonction de rappel appelé après le chargement de toutes les textures
		private var onLoadMethod:Function;
		// Index de la textire qui est en train d'être chargée
		private var currentTextureIndex:int;

		private var loader:Loader;
		private var request:URLRequest;
		private var loaderContext:LoaderContext;
		
		public function ObjetLoader(name:String=null) {
			super(name);
		}
		
		public function load(onLoadMethod:Function):String {
			if (bindings == null) {
				onLoadMethod.call();
			} else {
				this.onLoadMethod = onLoadMethod;
				request = new URLRequest();
				loaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
				loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.NETWORK_ERROR, onLoadError);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.VERIFY_ERROR, onLoadError);
				currentTextureIndex = 0;
				loadNextTexture();
			}
			return loadingMessage;
		}
		
		private function onLoadComplete(e:Event):void {
			var bitmapData:BitmapData = Bitmap(loader.content).bitmapData;
			bindings[currentTextureIndex++].texture = new Texture(bitmapData);
			loadNextTexture();
		}
		
		private function loadNextTexture():void {
			if (currentTextureIndex == bindings.length) {
				// Toutes les textures ont été chargées, fin du processus de chargement
				complete();
			} else {
				request.url = bindings[currentTextureIndex].textureUrl;
				loader.load(request, loaderContext);
			}
		}
		
		private function onLoadError(e:ErrorEvent):void {
			currentTextureIndex++;
			loadNextTexture();
		}
		
		private function complete():void {
			onLoadMethod.call();
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.NETWORK_ERROR, onLoadError);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.VERIFY_ERROR, onLoadError);
			onLoadMethod = null;
			loader = null;
			bindings = null;
		}
		
		
	}
}